<?php
namespace App\Http\Controllers\Backend\Sysconf;

use App\Exceptions\CommonException;
use App\Http\Controllers\Backend\BaseController;
use App\Http\Requests\Backend\Sysconf\paymentRequest;
use App\Repositories\PrtPaymentTypeRepository;
use Illuminate\Http\Request;

/**
 * 系统支付方式配置
 * @author:yanxs<541139655@qq.com>
 * @version: 1.0
 * @date:2021/7/13
 */
class PaymentController extends BaseController
{
    protected $viewPath = 'backend.sysconf.payment';  //当前控制器所的view所在的目录
    protected $modules = 'payment';         //当前控制器所属模块
    protected $codePrefix = '';         //编码前缀
    protected $payConfig;
    public function __construct(PrtPaymentTypeRepository $Repository)
    {
        parent::__construct();
        $this->repositories = $Repository;
        $payConfig = config("common.pay_conf");
        $this->payConfig = $kvConfig = array_column($payConfig, "name", "flag");
        view()->share("pay_type",$kvConfig);
    }
    /**
     * 通用表单展示
     * @param Request $request
     * @return mixed
     */
    protected function form(Request $request)
    {
        try {
            if($request->ajax())
            {
                $row = $this->repositories->getById($request->input('id'));
                //解析配置数据
                if (!empty ($row) && !empty($row['pay_config'])) {
                    $row[$row['pay_type']] = json_decode($row['pay_config'], true);
                }

                $htmlContents = $this->renderHtml($this->viewPath.'.'.$this->form, ['row' => $row]);
                return $this->jsonSuccess(['html' => $htmlContents]);
            }else{
                return view("admin.tips");
            }
        } catch (CommonException $e) {

            return $this->jsonFailed($e->getMessage());
        }

    }

   //添加/编辑操作
    public function save(paymentRequest $request)
    {
        $params = $request->all();
        $data['pay_name'] = $this->payConfig[$params['pay_type']];
        $data['id'] = $params['id'];
        $data['pay_type'] = $params['pay_type'];
        $data['logo'] = $params['logo'];
        $data['poundage'] = $params['poundage'];
        $data['desc'] = $params['desc'];
        if ($params['pay_type'] != 'balance') {
            $data['pay_config'] = json_encode($params[$data['pay_type']]);
        }
        $ret = $this->repositories->save($data);
        if ($ret) {
            return $this->jsonSuccess([]);
        } else {
            return $this->jsonFailed('');
        }
    }

}
